{*******************************************************************************
* The contents of this file are used with permission, subject to the Mozilla   *
* Public License Version 1.1 (the "License"); you may not use this file except *
* in compliance with the License. You may obtain a copy of the License at      *
* http://www.mozilla.org/MPL/                                                  *
*                                                                              *
* Software distributed under the License is distributed on an "AS IS" basis,   *
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for *
* the specific language governing rights and limitations under the License.    *
*                                                                              *
* The Original Code is distributed as part of the "mediate" product and is     *
* Copyright (C) @home media limited. All Rights Reserved.                      *
*                                                                              *
* Email: support@athomemedia.co.uk                                             *
* Web:   http://www.athomemedia.co.uk                                          *
*******************************************************************************}

unit SingleInstance;

interface

uses Windows;

function PreviousInstanceHandle: HWND;

var
  PreviousApplicationInstance: Boolean;


implementation

uses Messages, Forms, SysUtils;

const
  MUTEX_NAME = '@home media limited - mediate';

var
  MutexHandle: THandle;
  WindowCache: HWND;

function PreviousInstanceHandle: HWnd;
const
  MAX_LENGTH = 255;
var
  WindowClass, WindowCaption: array[0..MAX_LENGTH] of Char;
begin
  // Set default result - use cached value if available
  Result := WindowCache;
  if Result <> 0 then Exit;

  StrPCopy(WindowCaption, Application.MainForm.Caption);
  StrPCopy(WindowClass, Application.MainForm.ClassName);

  // Find another window with matching class and caption
	repeat
  	WindowCache := FindWindowEx(0, WindowCache, WindowClass, WindowCaption);
  until WindowCache <> Application.MainFormHandle;

  Result := WindowCache;
end;


initialization

  // Initialise other instance handle cache & create mutex
  WindowCache := 0;
  MutexHandle := CreateMutex(nil, True, MUTEX_NAME);

  // If mutex already exists then another instance is running
  if GetLastError = ERROR_ALREADY_EXISTS then
    PreviousApplicationInstance := True
  else
    PreviousApplicationInstance := False;


finalization
  if MutexHandle <> 0 then
    CloseHandle(MutexHandle);

end.
